package org.fqh.controller;

import javax.servlet.http.HttpSession;

import org.fqh.common.ResponseCode;
import org.fqh.entity.TUser;
import org.fqh.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.jdbc.StringUtils;

/**
* @author fqh 
* @version 创建时间：2018年3月20日 下午4:33:21
* 类说明 用户登录以及注册 
*/

@Controller
@RequestMapping("/user")
public class UserController {
	
	private static Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired 
	UserService userService;
	
	
	@GetMapping("/login")
	public String toLogin(HttpSession session) { 
		if(session.getAttribute("user")!=null) {
			return "redirect:/index";
		}else {
			return "/user/login";
		}
		
	}
	
	@GetMapping("/regist")
	public String toRegist() {
		return "user/regist"; 
	}
	
	 
	@PostMapping("/login")
	public @ResponseBody ResponseCode login(Model model,TUser user,HttpSession session) {
	
			ResponseCode responseCode = new ResponseCode() ;
		 
			try {
				TUser sessionUser =userService.CheckUserNamePassword(user);
				if(sessionUser==null) {
					responseCode.setCode(500);
					responseCode.setMsg("用户名或密码错误!"); 
				}else {
					responseCode.setMsg("登录成功");
					responseCode.setCode(200);
					responseCode.setUrl("/index");
					session.setAttribute("user",sessionUser);
				}
			} catch (Exception e) {
				responseCode.setMsg("系统错误"); 
				e.printStackTrace();
			}
    	
	    	return responseCode;
	}
	
	@ResponseBody
	@PostMapping("/regist")
	public String regist(Model model,TUser user) {
		//System.out.println(user.toString());
		try {
			userService.createTUser(user);
			return "success";
		}catch (Exception e) {
			return "fail";
		}
	
	}
	@GetMapping("/logout")
	public String logOut( HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/user/login";
	}
	
}
